import { NextResponse } from "next/server";
import { findUserByEmail } from "@/app/utils/db";
import { verifyPassword, signToken, setAuthCookie } from "@/app/utils/auth";

export const runtime = 'nodejs';

export async function POST(request) {
  try {
    const body = await request.json();
    const { email, password } = body || {};
    if (!email || !password) {
      return NextResponse.json({ error: "email and password are required" }, { status: 400 });
    }
    const user = findUserByEmail(email);
    if (!user) {
      return NextResponse.json({ error: "invalid credentials" }, { status: 401 });
    }
    const ok = await verifyPassword(password, user.password_hash);
    if (!ok) {
      return NextResponse.json({ error: "invalid credentials" }, { status: 401 });
    }
    const token = signToken({ sub: user.id, email: user.email });
    const res = NextResponse.json({ id: user.id, email: user.email, displayName: user.display_name });
    setAuthCookie(res, token);
    return res;
  } catch (e) {
    return NextResponse.json({ error: "invalid request", detail: String(e?.message || e) }, { status: 400 });
  }
}


